package kamikaze.service.user;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kamikaze.bean.User;
import kamikaze.bean.User.CardType;
import kamikaze.service.BusinessException;
import kamikaze.service.ErrorHandler;
import kamikaze.service.ExceptionUtil;
import kamikaze.utils.Database;
import kamikaze.utils.Database.Template;
import kamikaze.utils.StringUtil;

public class RegistrationServlet extends HttpServlet {

	private static final long serialVersionUID = 3391124362468713127L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		new ErrorHandler(Arrays.asList("Method is not supported")).handle(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		req.getSession().invalidate();

		ErrorHandler error = new ErrorHandler();

		try {

			String cardName = req.getParameter("cardName");
			error.addErrorMessageIfNotNull(StringUtil.ensureNotBlank(cardName, "card name"));

			String username = req.getParameter("loginId");
			error.addErrorMessageIfNotNull(StringUtil.ensureMatch(username,
					StringUtil.PATTERN_ALPHANUMERIC, "username needs to be alpha numeric"));

			String password = req.getParameter("password");
			error.addErrorMessageIfNotNull(StringUtil.ensureNotBlank(password, "password"));

			String email = req.getParameter("email");
			error.addErrorMessageIfNotNull(StringUtil.ensureNotBlank(email, "email"));

			String name = req.getParameter("name");
			error.addErrorMessageIfNotNull(StringUtil.ensureNotBlank(name, "name"));

			String cardNumber = req.getParameter("cardNumber");
			error.addErrorMessageIfNotNull(StringUtil.ensureMatch(cardNumber,
					StringUtil.PATTERN_ALPHANUMERIC, "username needs to be alpha numeric"));

			if (error.handle(req, resp)) {
				return;
			}

			final User user = new User();

			user.setCardName(cardName);
			user.setCardNumber(cardNumber);
			user.setCardType(CardType.valueOf(req.getParameter("cardType")));
			user.setExpiredDate(new SimpleDateFormat("mmyyyy").parse(req.getParameter("expiredDate")));

			user.setLoginId(username);
			user.setPassword(StringUtil.encrypt(password));

			user.setName(name);
			user.setEmail(email);

			user.setLastUpdateDate(new Date());
			user.setSuspended(true);

			Database.get().execute(new Template<Object>() {

				@Override
				public Object query(EntityManager em) {
					// make sure the login id is not there

					Number count = (Number) em.createQuery("select count(u) from User u where u.loginId = :loginId")
							.setParameter("loginId", user.getLoginId())
							.getSingleResult();

					if (count.intValue() != 0) {
						throw new BusinessException("login id is taken");
					}

					em.persist(user);

					return null;
				}
			});

			resp.sendRedirect("/index");
		} catch (Exception ex) {

			ExceptionUtil.logIfNecessary(ex);

			new ErrorHandler(Arrays.asList(ex.getMessage())).handle(req, resp);
			return;
		}
		resp.setContentType("text/html");
		resp.getWriter().append("registration successful <br/>").append("<a href='/index'>proceed to login</a>");

	}
}
